package com.haiheng.module_main.fragment
import android.annotation.SuppressLint
import android.app.ScansManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.haiheng.common.constant.Keys
import com.haiheng.common.constant.RourePage
import com.haiheng.common.dialog.StandardDialog
import com.haiheng.common.fragment.RouterFragment
import com.haiheng.library.log.LogUtils
import com.haiheng.library_base.adapter.BaseAdapter
import com.haiheng.library_base.dialog.LoadingDialog
import com.haiheng.library_base.model.ApplicationViewModel
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.library_base.msg.MsgCode
import com.haiheng.library_base.msg.MsgEvent
import com.haiheng.library_base.toast.ToastUtils
import com.haiheng.library_base.utils.FastClickUtil
import com.haiheng.module_main.R
import com.haiheng.module_main.adapter.BookReShelvingAdapter
import com.haiheng.module_main.databinding.FragmentBookReShelvingBinding
import com.haiheng.module_main.mode.AlarmedBooksViewModel
import com.haiheng.module_main.mode.BookInfoViewModel
import com.haiheng.module_main.mode.BookReShelvingViewModel
import com.haiheng.module_main.mode.BookRetirementViewModel

/**
 *
 * @Des: 图书理架
 * @Author: hwz
 * @Date:2023/6/17 0017
 * @Version: 1.0
 */
class BookReShelvingFragment : RouterFragment() {
    private lateinit var binding: FragmentBookReShelvingBinding
    private val viewMode : BookInfoViewModel by viewModels()
    private lateinit var bookReShelvingViewModel : BookReShelvingViewModel
    private lateinit var bookRetirementViewModel: BookRetirementViewModel
    private lateinit var alarmedBooksViewModel: AlarmedBooksViewModel
    private val bookListAdapter = BookReShelvingAdapter()
    private var mScansManager: ScansManager? = null
    private lateinit var loadingDialog : LoadingDialog
    private var layerInfoSureDialog  : StandardDialog? = null


    private val observer = Observer<MsgEvent> { msgEvent ->
        onMessageChange(msgEvent)
    }
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentBookReShelvingBinding.inflate(inflater, container, false)
        return binding.root
    }
    override fun initView() {
        loadingDialog = LoadingDialog(requireContext(), R.style.AvLoadingDialogStyle)
        bookRetirementViewModel = BookRetirementViewModel(viewMode)
        alarmedBooksViewModel = AlarmedBooksViewModel(viewMode)
        bookReShelvingViewModel = BookReShelvingViewModel(viewMode,bookRetirementViewModel,alarmedBooksViewModel)
        var pageType = arguments?.getString(Keys.PAGE_TYPE)
        if (RourePage.BOOK_INVENTORY.name.equals(pageType)){
            binding.includeTile.tvTitle.setText("图书盘点")
        }else{
            binding.includeTile.tvTitle.setText("图书理架")
        }
        binding.includeTile.ivBack.setOnClickListener {
            activity.navigateUp()
        }
        binding.includeTile.cbRignt.isChecked = false
        binding.includeIdentifyShelf.cbGetShelfNo.isChecked = true
        binding.includeTile.cbRignt.setOnClickListener {
            binding.includeTile.cbRignt.isChecked = true
            binding.includeIdentifyShelf.cbGetShelfNo.isChecked = false
//            mScansManager?.startScan()
        }
        binding.includeIdentifyShelf.cbGetShelfNo.setOnClickListener {
            binding.includeTile.cbRignt.isChecked = false
            binding.includeIdentifyShelf.cbGetShelfNo.isChecked = true
//            mScansManager?.startScan()
        }

        binding?.rvBookList?.layoutManager = LinearLayoutManager(activity)
        binding?.rvBookList?.adapter = bookListAdapter

        bookListAdapter.setOnItemClickListener(object : BaseAdapter.OnItemClickListener{
            override fun onItemClick(holder: BaseAdapter.ViewBindHolder, position: Int) {
                var bookInfoBean = bookListAdapter.getItem(position)
                bookInfoBean.isSelect = !bookInfoBean.isSelect
                var isAllSelet = true
                for (b in bookListAdapter.getData()){
                    if (!b.isSelect){
                        isAllSelet = false
                        break
                    }
                }
                bookListAdapter.notifyDataSetChanged()
            }
        })


        binding.includeIdentifyShelf.etShelfNo.setOnEditorActionListener {  v, keyCode, event ->
            LogUtils.e("ddddddd  keyCode${keyCode}")
            if(keyCode == EditorInfo.IME_ACTION_SEARCH) {
                binding.tvShelfNo.text = ""
                viewMode.getShelName(binding.includeIdentifyShelf.etShelfNo.text.toString())
                false
            }
            false
        }
    }

    override fun onResume() {
        super.onResume()
        observEven()
    }

    override fun onPause() {
        super.onPause()
        clearMsg()
        mScansManager?.stopScan()
    }

    override fun initViewModel(): BaseViewModel? {

        bookReShelvingViewModel.onShelfNum.observe(viewLifecycleOwner){
            binding.tvShelfNum.setText("在架：${it.toString()}")
        }
        bookReShelvingViewModel.notOnShelfNum.observe(viewLifecycleOwner){
            binding.tvNotOnShelf.setText("不在架：${it.toString()}")
        }
        bookReShelvingViewModel.wrongShelfNum.observe(viewLifecycleOwner){
            binding.tvWrongShelfNum.setText("错架：${it.toString()}")
        }
        bookReShelvingViewModel.alarmedNum.observe(viewLifecycleOwner){
            binding.tvAlarmedNum.setText("其中包含      报警：${it.toString()}")
        }
        bookReShelvingViewModel.retirementNum.observe(viewLifecycleOwner){
            binding.tvRetirementNum.setText("剔旧：${it}")
        }
        viewMode.isFinishSearch.observe(viewLifecycleOwner){
            bookReShelvingViewModel.updataRetirementAndAlarmedNum()
        }
        viewMode.bookListData.observe(viewLifecycleOwner){
            binding.tvBookNum.setText("数量：${it.size}")
            bookListAdapter.setNewData(it)
            bookReShelvingViewModel.calculateNotOnShelfNum()
        }
        viewMode.showMsg.observe(viewLifecycleOwner){
            ToastUtils.showShort(it)
            loadingDialog.hide()
        }
        viewMode.layerInfo.observe(viewLifecycleOwner){ it->
            var content = "层架号：${it.outValue} \n名称：${it.name}"
            var listener  = object : StandardDialog.OnDialogClickListener{
                override fun onConfirm(dialog: StandardDialog) {
                    binding.tvShelfNo.text = it.name
                    //清除之前理架的统计
                    bookReShelvingViewModel.clearNum()
                    viewMode.searchBookLisbByCurrentContainerId(it.outValue.toString())
                    binding.includeTile.cbRignt.performClick()
                    dialog.dismiss()
                }

                override fun onCancel(dialog: StandardDialog) {
                    dialog.dismiss()
                }
            }
            if (layerInfoSureDialog == null){
                layerInfoSureDialog = StandardDialog.newInstance().setTitle(getString(R.string.hint_layer_no))
            }
            layerInfoSureDialog?.setOnDialogListener(listener)
            layerInfoSureDialog?.setContent(content)
            LogUtils.e("dddddddddd usAdd: ${layerInfoSureDialog?.isAdded}  isVisible:${layerInfoSureDialog?.isVisible}")
            if (!layerInfoSureDialog!!.isAdded){
                layerInfoSureDialog?.show(childFragmentManager)
            }
        }
        viewMode._bookInfoByBarcode.observe(viewLifecycleOwner){
            bookReShelvingViewModel.updataNum(it,binding.tvShelfNo.text.toString())
        }
        bookRetirementViewModel._bookRetirementData.observe(viewLifecycleOwner){
        }

        return viewMode
    }

    private fun onMessageChange(msgEvent: MsgEvent?) {
        when (msgEvent?.code){
            MsgCode.MSG_SCANS_BARCODE->{
                if (FastClickUtil.isFaskMsg(msgEvent.msg,200)) return //两次相同消息太快这不处理
                if (binding.includeIdentifyShelf.cbGetShelfNo.isChecked){
                    if (layerInfoSureDialog?.isVisible == true)return
                    binding.includeIdentifyShelf.etShelfNo.setText(msgEvent.msg)
                    binding.tvShelfNo.text = ""
                    viewMode.getShelName(msgEvent.msg)
                }
                if (binding.includeTile.cbRignt.isChecked){
                    viewMode.searchBookInfoByBarCode(msgEvent.msg)
                }
            }
        }
    }

    private fun observEven() {
        if (ApplicationViewModel.get().even != null) {
            if (ApplicationViewModel.get().even.hasObservers()) {
                ApplicationViewModel.get().even.removeObserver(observer)
            }
            ApplicationViewModel.get().even.observe(this,observer)
        }
    }
    fun clearMsg(){
        if (ApplicationViewModel.get().even != null) {
            if (ApplicationViewModel.get().even.hasObservers()) {
                ApplicationViewModel.get().even.removeObserver(observer)
            }
        }
    }

    @SuppressLint("WrongConstant")
    override fun initLoad() {
        var manager   = activity.getSystemService("scans")
        if (manager != null){
            mScansManager = manager as ScansManager
            mScansManager?.persistMode =true
        }
        bookRetirementViewModel.searchBookRetirement()
        alarmedBooksViewModel.searchAlarmedBooks()
    }

}